import axios from 'axios'

import context from '../main.js'

import {Toast} from 'vant';

//封装axios
const request = (url, method = 'GET', data = {}) => {
	
	return new Promise((resolve, reject) => {
		axios({
			
			method: method,
			url: url,
			data: data,
			//dataType: 'json',
			headers: {
				'Set-Cookie': 'PHPSESSID=' + localStorage.getItem("Set-Cookie")
				// 'Set-Cookie': 'PHPSESSID=e53e9f0fc434589e36155d9f308e981b' 
			}
		}).then(function(res) {
			resolve(res)
		}).catch(function(error) {
			reject(error)
		})
	})
}


//设置请求域名
let BASE_URL;

//判断 本地运行环境(development)   与   打包线上环境(production)  设置axios请求的默认域名 
if (process.env.NODE_ENV == 'development') {
	//这里使用了/api 即vue.config.js配置的代理的域名
	BASE_URL = '/api'

} else {
	//npm run build 打包后使用的线上域名
	BASE_URL = 'http://www.bsnqwpg.cn'

}

//公共请求方法
export const sendAjax = (
	api_url,
	method = 'GET',
	params = {},
	resolve,
	reject
) => {
	//用户登录 access_token
	// params.access_token = access_token.getAccessToken()
	
		
	//用户 access_token
	params.cookie=localStorage.getItem("Set-Cookie");

	request(BASE_URL + api_url, method, params)
	
		.then(function(res) {
			//失败: 直接返回
			
			if(res.data.code == -1){
				
				// Toast(res.data.msg)
				
				//所有请求判断账号过期
				Toast("账号身份已过期,请重新登陆")
				
				setTimeout( () => {

					context.$router.push('/login')	
					
				},1000)
			
			}
			
			
			
			resolve({
				data:res.data
			})
			
			// resolve({
			// 	code: res.code,
			// 	msg: res.msg
			// }, res)
			
		})
		.catch(function(error) {
			if (typeof resolve === 'function') {
				reject(error)
			}
		})
}